#!/usr/bin/env python2
"""
module to get movies and tv shows from icefilms
"""

from lxml.html 
from lxml.html import parse
import urllib,urllib2,cookielib,base64
import random
import re
import delta

MODULE = 'icefilms'
ICEFILMS_AJAX = 'http://www.icefilms.info/membersonly/components/com_iceplayer/video.phpAjaxResp.php'
ICEFILMS_REFERRER = 'http://www.icefilms.info'
USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'

def geturl(url, params = None, referrer = ICEFILMS_REFERRER, cookie = None, get_cookie = False):
    if params:
        req = urllib2.Request(url, params)
        # req.add_header('Content-type', 'application/x-www-form-urlencoded')
    else:
        req = urllib2.Request(url)
    #    
    req.add_header('User-Agent', USER_AGENT)
    #
    if referrer:
        req.add_header('Referer', referrer)
    #
    if cookie:
        req.add_header('Cookie', cookie)
    #
    response = urllib2.urlopen(req)
    body = response.read()
    #
    if get_cookie:
        setcookie = response.info().get('Set-Cookie', None)
        if setcookie:
            setcookie = re.search('([^=]+=[^=;]+)', setcookie).group(1)
        body2=lxml.html.document_fromstring(body)
        response.close()
        return (body2, setcookie)
    #
    body2=lxml.html.document_fromstring(body)
    response.close()
    return body2
    
def GetSource(page, id, cookie):
    page=lxml.html.tostring(response)
    params = {
    'iqs': '',
    'url': '',
    'cap': ''
    }
    sec = re.search("f\.lastChild\.value='([^']+)';", page).group(1)
    t   = re.search('"&t=([^"]+)";', page).group(1)
    params['sec'] = sec
    params['t'] = t
    #
    m = random.randrange(100, 300) * -1
    s = random.randrange(5, 50)
    #params = copy.copy(args)
    params['id'] = id
    params['m'] = m
    params['s'] = s
    paramsenc = urllib.urlencode(params)
    body = geturl(ICEFILMS_AJAX, params = paramsenc, cookie = cookie)
    url= urllib.unquote(body.xpath('//p')[0].text.partition('?url=')[-1])[:-1]
    return url

def movies():
    """
    gets the movie list in the format : 
    [{"NAME":"Rio (2011)", "URL":"url of page that contails a list of video hosts", "TYPE":"MOVIE" }]
    and returns a list
    """
    url="http://www.icefilms.info/movies/a-z/"
    ulist="1ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    #ulist="1"
    l = []
    for i in ulist: 
        turl=url+i
        temp = geturl(turl)
        raw_list =  temp.xpath('//span[@class="list"]/a[@href]')
        for i in range((len(raw_list))) :
            d = {}
            d["NAME"] = raw_list[i].text
            d["URL"] = "http://www.icefilms.info"+raw_list[i].attrib["href"]
            l.append(d)
    l = returnsOriginalData(l, 'movies', MODULE, tvshowName=None)
    return l    



def tvShows():
    """
    gets the name of each show along wiht 
    [{"NAME":"3rd Rock from the Sun", "URL":"url of page that contails a list of episodes"}]
    """
    url="http://www.icefilms.info/tv/a-z/"
    #ulist="1ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    ulist="1"
    l=[]
    for i in ulist: 
        turl=url+i
        for i in geturl(turl).xpath('//span[@class="list"]/a[@href]'):
            d = {} 
            d["URL"] = "http://www.icefilms.info"+i.attrib["href"] 
            d["NAME"] = i.text
            l.append(d)
    l = returnsOriginalData(l, 'tvShows', MODULE, tvshowName=None)        
    return l    

def episodes(turl,tvshowName):
    """
    returns a list of episodes for a show alog with url of page containing the list of vide host urls
    [{"EPISODE":"1x02 Post-Nasal Dick", "URL":"url of page that contails a list of video hosts"}]
    """
    l=[]
    for i in geturl(turl).xpath('//span[@class="list"]/a[@href]'): 
        d={}
        d["EPISODE"] = i.text
        d["URL"] = "http://www.icefilms.info"+i.attrib["href"]
        l.append(d)
    l = returnsOriginalData(l, 'tvShows', MODULE, tvshowName)        
    return l

def get_video_urls(urls):
    """
    returns a list of video host urls
    """
    raw_video_list_page = "http://www.icefilms.info"+geturl(urls).xpath("//div[@id='videotitle']/div/a")[0].attrib["href"]
    (response, cookie) =  geturl(raw_video_list_page, get_cookie = 'True')
    temp=0
    l=[]
    for i in response.xpath('//div[@id="srclist"]/div[@class="ripdiv"]/p/a[@rel]'): 
        if temp==int(i.attrib["rel"]):
            id=i.attrib["onclick"][3:-1] 
            l[int(i.attrib["rel"])-1].append([GetSource(response, id, cookie)])
        else:
            id=i.attrib["onclick"][3:-1]       
            l.append([GetSource(response, id, cookie)])
        temp=int(i.attrib["rel"])
    return l
    

    
    

if __name__ == "__main__":
